<template>
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    style="color: red"
    title="挂载内容-小黄车"
    placement="right"
    width="600px"
    @close="onClose"
    :maskClosable="false"
  >
    <!-- 小黄车 -->
    <a-spin :spinning="spinning">
      <div class="yellow-cart">
        <!-- 标题 -->
        <div class="title">
          抖音账号
          <a-tooltip>
            <template #title>仅支持抖音账号开通小黄车功能挂载商品</template>
            <question-circle-outlined style="margin-left: 3px" />
          </a-tooltip>
        </div>
        <a-form
          style="margin-top: 10px; width: 100%"
          layout="inline"
          ref="formRef"
          :model="formState"
        >
          <div style="display: flex; width: 100%">
            <a-form-item
              style="margin-bottom: 5px !important"
              name="id"
              :rules="[{ required: true, message: '请选择添加购物车账号!' }]"
            >
              <a-select
                placeholder="请选择添加购物车账号"
                style="width: 200px"
                v-model:value="formState.id"
                :options="selectOptions"
                @change="handSelectChange"
                allowClear
              ></a-select>
            </a-form-item>
            <a-form-item
              style="flex: 1"
              name="promotion_link"
              :rules="[{ required: true, message: '请输入商品链接!' }]"
            >
              <!-- 搜索框 -->
              <div class="search_box">
                <a-input
                  placeholder="请输入商品链接"
                  v-model:value="formState.promotion_link"
                  allowClear
                ></a-input>
                <a-button @click="addLinkHandle" :loading="addLinkLoading"
                  >添加链接</a-button
                >
              </div>
            </a-form-item>
          </div>
        </a-form>

        <!-- 已添加商品列表 -->
        <!-- 标题 -->
        <div class="title" style="margin-top: 10px">已添加商品</div>
        <div class="cart_list" v-if="countShopList.length">
          <div class="cart_item" v-for="item in countShopList">
            <!-- 商品图片 -->
            <div class="product_picture">
              <img
                :src="item?.good_imgs[0]?.img"
                v-lazy="item?.good_imgs[0]?.img"
                alt=""
              />
            </div>
            <!-- 商品信息 -->
            <div class="product_info">
              <!-- 商品名称 -->
              <div class="product_name">
                <!-- <a-button size="small" ghost type="primary">小店</a-button> -->
                <img :src="item.brand_icon" alt="" />
                {{ item?.title }}
              </div>
              <!-- 短标题 -->
              <div class="product_sort_title">
                短标题:{{ item?.elastic_title }}
              </div>
              <!-- 价格 -->
              <div class="product_price">
                <div>
                  <span style="margin-right: 5px"
                    >每单赚
                    <span class="price_color">{{
                      item?.cos_fee_text
                    }}</span></span
                  ><span
                    >售价 <span>{{ item?.price_text }}</span></span
                  >
                </div>
                <div>
                  <a-space>
                    <a-button size="small" @click="editLinkHandle(item)"
                      >编辑</a-button
                    ><a-button size="small" @click="delHandle(item)"
                      >移除</a-button
                    >
                  </a-space>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="cart_list" v-else>
          <a-empty :image="simpleImage" />
        </div>
      </div>
    </a-spin>
    <!-- 底部按钮 -->
    <template #footer>
      <div style="text-align: right">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="submitHandle">确定</a-button>
      </div>
    </template>
  </a-drawer>
  <!-- 编辑商品组件 -->
  <EditProductModel ref="editProductModel" @success="editProductModelSuccess" />
</template>

<script>
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  computed,
  createVNode,
} from "vue";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import request from "../../../../common/utils/request";
import EditProductModel from "./editProductModel.vue";
import { type } from "jquery";
import { Empty } from "ant-design-vue";
import { Modal } from "ant-design-vue";
export default defineComponent({
  props: {
    accountList: {
      type: Array,
      default: () => [],
    },
    cartList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    PlusOutlined,
    EditProductModel,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
  },
  setup(props, context) {
    const state = reactive({
      visible: false,
      formState: {
        id: null,
        promotion_link: "",
      },
      addLinkLoading: false,
      productList: [], //购物车列表
      delLoading: false,
      selectOptions: [], //下拉列表
      countShopList: [], //每个账号对应的购物车列表
      spinning: false,
    });
    // 打开弹窗
    const showDrawer = () => {
      state.productList = JSON.parse(JSON.stringify(props.cartList));
      getSelectList();
      state.visible = true;
    };
    // 获取账号
    const AccountList = computed(() => {
      return props.accountList;
    });
    // 获取可绑定小黄车的账号下拉列表
    const getSelectList = () => {
      let params = {
        account_ids: AccountList.value.map((item) => item.id),
      };
      state.spinning = true;
      request
        .post("/work_ai", "/org/platformAccount/filter/accountCarts", params)
        .then((res) => {
          if (!res.result.length) {
            state.spinning = false;
            return message.warn("所选账号暂无挂载小黄车权限");
          } else {
            state.selectOptions = res.result.map((item) => {
              return {
                label: item.nickname,
                value: item.id,
              };
            });
            state.formState.id = state.selectOptions[0].value;
            state.countShopList = state.productList.filter(
              (item) => item.id == state.formState.id
            );
          }
          state.spinning = false;
        })
        .catch((err) => {
          state.spinning = false;
        });
    };
    // 关闭弹窗
    const onClose = () => {
      state.visible = false;
      formRef.value.resetFields();
    };
    const editProductModel = ref(null); //编辑商品组件实例
    const formRef = ref(null);
    // 添加商品链接
    const addLinkHandle = () => {
      formRef.value &&
        formRef.value
          .validate()
          .then(() => {
            state.addLinkLoading = true;
            request
              .get("/work_ai", "/org/platformAccount/douyin/userCart", {
                id: state.formState.id,
              })
              .then((res) => {
                // 判断该账号是否还可以追加购物车商品
                if (res.result.is_over_bind_cnt == true) {
                  message.error("该账号购物车数量已达上限");
                  state.addLinkLoading = false;
                } else {
                  // 根据商品链接获取商品
                  request
                    .get(
                      "/work_ai",
                      "/org/platformAccount/douyin/promotionLink",
                      {
                        ...state.formState,
                      }
                    )
                    .then((res) => {
                      state.addLinkLoading = false;
                      if (res.result) {
                        let findIndex = state.productList.findIndex(
                          (item) =>
                            item.unique_product_id ==
                            res.result.unique_product_id
                        );
                        if (findIndex == -1) {
                          editProductModel.value &&
                            editProductModel.value.showModal({
                              productDetail: {
                                ...res.result,
                              },
                              productList: state.productList,
                              openType: "add",
                            });
                        } else {
                          message.warning("已存在重复商品");
                        }
                      }
                    })
                    .catch((err) => {
                      state.addLinkLoading = false;
                    });
                }
              })
              .catch((err) => {
                console.log(err, "ksdkksksdk");
                state.addLinkLoading = false;
              });
          })
          .catch((err) => {});
    };
    const editLinkHandle = (info) => {
      editProductModel.value &&
        editProductModel.value.showModal({
          productDetail: {
            ...info,
          },
          productList: state.productList,
          openType: "edit",
        });
    };
    // 添加购物车成功回调
    const editProductModelSuccess = (info) => {
      state.productList = info;
      state.countShopList = info.filter(
        (item) => item.id == state.formState.id
      );
    };
    // 删除
    const delHandle = (info) => {
      Modal.confirm({
        title: "删除商品",
        icon: createVNode(ExclamationCircleOutlined),
        content: "确定删除商品吗？",
        cancelText: "取消",
        okText: "确定",
        onOk() {
          let delIndex = state.productList.findIndex(
            (item) => item.unique_product_id == info.unique_product_id
          );
          if (delIndex != -1) {
            let arrList = JSON.parse(JSON.stringify(state.productList));
            arrList.splice(delIndex, 1);
            state.delLoading = true;
            let params = {
              id: info.id,
              draft_id: info.draft_id,
            };
            let filterList = arrList.filter((item) => item.id == info.id);
            if (filterList.length > 0) {
              params.raw_draft = filterList;
            }
            request
              .post(
                "/work_ai",
                "/org/platformAccount/douyin/draftUpdate",
                params
              )
              .then((res) => {
                state.delLoading = false;
                state.productList.splice(delIndex, 1);
                state.countShopList.splice(delIndex, 1);
                message.success("删除成功");
              })
              .catch((err) => {
                state.delLoading = false;
              });
          }
        },
        onCancel() {},
      });
    };
    // 点击确定
    const submitHandle = () => {
      context.emit("success", state.productList);
      state.visible = false;
    };
    const handSelectChange = () => {
      state.countShopList = state.productList.filter(
        (item) => item.id == state.formState.id
      );
    };
    // 添加标题
    return {
      ...toRefs(state),
      showDrawer,
      onClose,
      addLinkHandle,
      editProductModel,
      formRef,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      editProductModelSuccess,
      editLinkHandle,
      delHandle,
      submitHandle,
      AccountList,
      handSelectChange,
    };
  },
});
</script>

<style lang="less" scoped>
.yellow-cart {
  width: 100%;
  .title {
    color: black;
  }
  .search_box {
    width: 100%;
    display: flex;
  }
  .cart_list {
    width: 100%;
    margin-top: 10px;
    max-height: 560px;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 8px; /* 滚动条的宽度 */
      height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #888; /* 滑块的背景颜色 */
      border-radius: 10px; /* 滑块的圆角 */
      width: 8px !important; /* 滚动条的宽度 */
      height: 5px !important;
    }
    .cart_item {
      display: flex;
      margin-top: 10px;
      width: 100%;
      height: 100px;
      // border: 1px solid pink;
      align-items: center;
      .product_picture {
        background-color: #d7d7d7;
        width: 100px;
        height: 100px;
        margin-right: 10px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .product_info {
        flex: 1;
        height: 100px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        font-size: 14px;
        padding: 5px 0;
        .product_name {
          max-width: 400px;
          white-space: nowrap; /* 防止文本换行 */
          overflow: hidden; /* 隐藏溢出内容 */
          text-overflow: ellipsis; /* 显示省略号 */
          color: black;
          img {
            width: 35px;
            object-fit: cover;
          }
        }
        .product_sort_title {
          width: 100%;
          color: rgba(38, 38, 38, 0.8);
          max-width: 400px;
          white-space: nowrap; /* 防止文本换行 */
          overflow: hidden; /* 隐藏溢出内容 */
          text-overflow: ellipsis; /* 显示省略号 */
        }
        .product_price {
          display: flex;
          justify-content: space-between;
          color: rgba(38, 38, 38, 0.8);
          .price_color {
            color: var(--ss-primary-color);
          }
        }
      }
    }
  }
}
</style>
